<?php

namespace User\Controller;
use Common\Controller\FrontbaseController;

class ApiController extends FrontbaseController
{
	protected $user_model;
	protected $user_favorites_model;
	const session_expire = "86400";//session过期时间

	public function _initialize()
	{
		parent::_initialize();
		$this->user_model = D('User/Users');
		$this->user_favorites_model = D('User/UserFavorites');
	}

	/*注册*/
	public function register()
	{
		$mobile = I("mobile");//用户手机
		$where['mobile'] = $mobile;
		/*验证是否已经注册--防止多次注册*/
		$existence = $this->user_model
			->where($where)
			->find();
		if (!$existence) { //未注册
			$password = I("password");//密码
			$data['mobile'] = $mobile;
			$data['user_pass'] = sp_password($password);//生成加密密码
			$data['create_time'] = time();
			$data['user_type'] = '1'; //用户类型，1:用户 ;2:普通员工3:VIP会员4:超级VIP会员
			$userRegisterStatu = $this->user_model
				->data($data)
				->add();
			if ($userRegisterStatu) {
				$arr['status'] = '1';
				$arr['msg'] = '注册成功';

			} else {
				$arr['status'] = '0';
				$arr['msg'] = '注册失败';
			}
		} else {
			$arr['status'] = '2';
			$arr['msg'] = '此用户已注册';
		}
        $this->output($arr);
	}

	/*判断此用户是否已注册*/
	public function is_registered()
	{
		$mobile = I("mobile");//用户手机
		$where['mobile'] = $mobile;
		$existence = $this->user_model
			->where($where)
			->find();
		if (!$existence) {
			$arr['status'] = '1';
			$arr['msg'] = '未注册此用户';
			$this->output($arr);
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '此用户已注册';
			$this->output($arr);
		}
	}

	/*登录*/
	public function login()
	{
	    	//step1:查询手机号
		$mobile = I("mobile");//用户手机	
		$where['mobile'] = $mobile;
		$where['user_status'] = '1'; //启用客户--拉黑客户禁止登陆
		$user_verify = $this->user_model->where($where)->find();
		//step2:查询对比密码
		$password = I("password");//密码
		$is_user = sp_compare_password($password, $user_verify['user_pass']);
		
		$data['last_login_time'] = time();
		//更新最后登录时间
		$upTime = $this->user_model
			->where($where)
			->save($data);
		
		if ($is_user) {
			session('user',$user_verify);
			//更新登录状态
			D('Common/Session') -> update(array(
					'user_id' => $user_verify['id'],
					'login_time' => NOW_TIME,
					'logged' => 1)
			);
			//成功状态
			$arr['status'] = '1';
			$arr['msg'] = '登录成功';
			$arr['user_info'] = $user_verify;
			$this->output($arr);
		} else {
		    //失败状态
			$arr['status'] = '0';
			$arr['msg'] = '登录失败';
			$this->output($arr);
		}
	}

    /**
     * 找回密码
     * @author 郝飞
     */
	public function retrieve_password()
	{
		$mobile = I("mobile");//用户手机
		$password = I("password");//密码
		$new_password = sp_password($password);
		$data['user_pass'] = $new_password;
		$where['mobile'] = $mobile;
		$status = $this->user_model
			->where($where)
			->save($data);
		if ($status !== false) {
			$arr['status'] = '1';
			$arr['msg'] = '重设成功';
			$this->output($arr);
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '重设失败,请稍后再试';
			$this->output($arr);
		}
	}


    /*
     * 未登录找回密码
     * @author 杨红伟
     */
    public function changePassword(){

        $user_phone = I("mobile");
        $password = I("password");
        $result = $this->user_model->where("mobile = $user_phone")->save(array('user_pass'=>sp_password($password)));
        if ($result == 1 ) {
            $res['msg'] = '密码重置成功';
            $res['status'] = 1;
        } else if($result == 0 ){
            $res['msg'] = '密码与以前的相同，请重新设置';
            $res['status'] = 0;
        }else{
            $res['msg'] = '重置密码失败';
            $res['status'] =2;
        }
        $this->output($res);
    }

	/*更改用户手机号和用户昵称*/
	public function updataInfo()
	{
		$user = session('user');
		if(!$user['id']){
			$arr['error'] = '201';
			$arr['error_msg'] = '请先登录';
			$this->output($arr);
			exit;
		}else{
			$is_block = \User\Lib\ImiLib::getUserById($user['id']);
			if($is_block['user_status'] != 1){
				$arr['error'] = '201';
				$arr['error_msg'] = '您已被工作人员拉黑';
				$this->output($arr);
				exit;
			}
		}
		//字段名
		$fieldName = I("fieldName");
		//输入信息
		$information = I("information");
		//获取用户资料
		$userInfo = session('user');

		$data[$fieldName] = $information;
		$result = $this->user_model
			->where("id = $userInfo[id]")
			->save($data);
		if ($result !== false) {
			$arr['status'] = '1';
			$arr['msg'] = '更新成功';
			$this->output($arr);
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '更新失败';
			$this->output($arr);
		}
	}

	/*用户上传头像*/
	public function updataImage()
	{
		//用户ID
		$user = session('user');
		$uid = $user['id'];
		//上传图片路径
		$imageURL = $_FILES['upfile'];
		/*图片上传*/
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize = 3145728;// 设置附件上传大小
		$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->rootPath = './' . C("UPLOADPATH"); // 设置附件上传根目录
		$upload->savePath = './avatar_big/'; // 设置附件上传（子）目录
		$upload->subName = null;

		/*上传图片*/
		$image_info = $upload->uploadOne($imageURL);
		$file_path_B = './data/upload/avatar_big/' . $image_info['savename'];

		/*缩略图*/
		$file_path_S = './data/upload/avatar/' . $image_info['savename'];
		$image = new \Think\Image(); //生成缩略图类
		$image->open($file_path_B);
		$info = $image->thumb(150, 150)->save($file_path_S);//生成一个150*150的缩略图并保存为原图的名称

		if (!$info) {
			$arr['status'] = '0';
			$arr['msg'] = '上传失败';
		} else {
			//上传图片名
			$avatar = $image_info['savename'];
			$user_info = $this->user_model->find($uid);
			//旧头像
			$old_img = $user_info['avatar'];
			$result = $this->user_model->where(array('id' => $uid))->save(array("avatar" => $avatar));
			if ($result !== false) {
				// 删除旧的头像
				$old_S_Img = 'data/upload/avatar/' . $old_img;
				$old_B_Img = 'data/upload/avatar_big/' . $old_img;
				delete_avatar($old_S_Img);
				delete_avatar($old_B_Img);
				$arr['status'] = '1';
				$arr['ImageInfo'] = $avatar;
				$arr['msg'] = '上传成功';
				$this->output($arr);
			} else {
				$arr['status'] = '0';
				$arr['msg'] = '上传失败';
				$this->output($arr);
			}
		}
	}



	/*退出登录*/
	public function quit()
	{
		session('user', null);
		//判断session是否清空
		if (session('user')) {
			$arr['status'] = '0';
			$arr['msg'] = '用户注销失败';
			$this->output($arr);
		} else {
			$arr['status'] = '1';
			$arr['msg'] = '用户注销';
			$this->output($arr);
		}

	}

	/**
	 * [collect 用户收藏列表]
	 * @return [json] [数据和状态]
	 */
	public function collect() {
		$user = session('user');
		$user_id = $user['id'];
		$start = I('start');		//开始位置
		$limit = I('limit');		//显示数量
		$db_prefix=C('DB_PREFIX');
		$result = $this
			->user_favorites_model
			->alias('a')
			->join($db_prefix.'portal_posts as b on a.object_id = b.id')
			->where("a.uid = ".$user_id)
			->limit($start,$limit)
			->select();
		foreach ($result as &$value) {
			$value['smeta'] = json_decode($value['smeta'],ture);
			$value['thumb'] = $value['smeta']['thumb'];
		}
		//返回
		if ($result) {
			$assign['status'] = 1;
			$assign['msg']  = '获取用户收藏列表 成功';
			$assign['info'] = $result;
		} else {
			$assign['error'] = 1;
			$assign['error_msg'] = '获取用户收藏列表 没有数据';
		}

		//输出
		$this -> output($assign);
	}

	//提交留言
	public function submitGuestbook()
	{
		$user = session('user');
		if(!$user['id']){
			$arr['error'] = '201';
			$arr['error_msg'] = '请先登录';
			$this->output($arr);
			exit;
		}else{
			$is_block = \User\Lib\ImiLib::getUserById($user['id']);
			if($is_block['user_status'] != 1){
				$arr['error'] = '201';
				$arr['error_msg'] = '您已被工作人员拉黑';
				$this->output($arr);
				exit;
			}
		}
		$text = I('info');
		$userInfo = session('user');
		$data['user_id'] = $userInfo['id'];
		$data['mobile'] = $userInfo['mobile'];
		$data['createtime'] = time();
		$data['msg'] = $text;

		// 增加操作
		$rst = D('Tools/ToolsGuestbook')->add($data);
		// 判断返回结果
		if ($rst) {
			$arr['status'] = '1';
			$arr['msg'] = '您已提交成功！';
			$this->output($arr);
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '提交失败！';
			$this->output($arr);
		}
	}



	/**
	 * 获取用户信息接口
	 * @param    number $user_id 用户ID或ID数组
	 */
	public function userInfo($user_id = 0) {

		//申明变量
		$error = 0;
		$error_msg = '';
		$multi = strpos($user_id, ',');

		//查出用户
		if ($multi) {
			$user =\User\Lib\ImiLib::getUserByIds($user_id);
		} else {
			$user =  \User\Lib\ImiLib::getUserById($user_id);
		}

		$assign['error'] = $error;
		$assign['error_msg'] = $error_msg;
		$assign['status'] = intval(!$error);
		$assign['user'] = $user;
		$this->output($assign);

	}



	//用户列表-除自己的
	public function userlist(){

		//用户ID
		$user_id = \User\Lib\ImiLib::getCurrentUserId();

		//不包含自己
		if($user_id) {
			$where['id'] = array('NEQ',$user_id);
		}else{
			$this->quit();
		}
		//查询
		$userlist = D('users')->where($where)->select();

		//头像处理
		foreach ($userlist as $key =>$value) {
			$userlist[$key]['avatar'] = sp_get_user_avatar_url($value['avatar']);
		}

		//返回
		if ($userlist) {
			$assign['status'] = 1;
			$assign['msg']  = '获取用户列表成功 成功';
			$assign['info'] = $userlist;
		} else {
			$assign['error'] = 1;
			$assign['error_msg'] = '获取用户列表失败';
		}
		$this->output($assign);

	}

	//用户列表-力拓专用-除自己的
	public function userlist_lituo(){
		$user = session('user');
		if(!$user['id']){
			$arr['error'] = '201';
			$arr['error_msg'] = '请先登录';
			$this->output($arr);
			exit;
		}else{
			$is_block = \User\Lib\ImiLib::getUserById($user['id']);
			if($is_block['user_status'] != 1){
				$arr['error'] = '201';
				$arr['error_msg'] = '您已被工作人员拉黑';
				$this->output($arr);
				exit;
			}
		}

		//step1:传参
		$user_type = I('user_type/d');
		$job_class = I('job_class/d');

		//step2:用户ID
		$user_id = \User\Lib\ImiLib::getCurrentUserId();
		//step3:查询条件
		$where['id'] = array('NEQ',$user_id); //不包含自己
		if($user_type) {
			$where['user_type'] = $user_type; //用户类型：1:用户 ;2:普通员工
		}
		if($job_class) {
			$where['job_class'] = $job_class; 	//咨询师：0普通员工/用户 1优质咨询师 2VIP咨询师 3超级VIP咨询师
		}
//		$where ['status'] = array('NEQ','1');
		$userlist = D('users')->where($where)->select();

		//step4:头像处理
		foreach ($userlist as $key =>$value) {
			$userlist[$key]['avatar'] = sp_get_user_avatar_url($value['avatar']);
		}

		//step5:返回及输出
		if ($userlist) {
			$assign['status'] = 1;
			$assign['msg']  = '获取咨询师用户列表成功 成功';
			$assign['info'] = $userlist;
		} else {
			$assign['error'] = 1;
			$assign['error_msg'] = '获取咨询师用户列表 暂时没有数据！';
		}
		$this->output($assign);

	}


    /**
     * [verifyOldPassword 判断旧密码是否正确]
     * @return [json] [状态]
     */
    public function verifyOldPassword() {
        $user = session('user');
        $user_id = $user['id'];
        $password = I("password");
        $userInfo= $this->user_model->field("user_pass")->find($user_id);
        $result = sp_compare_password($password,$userInfo['user_pass']);
        if ($result) {
            $arr['status'] = 1;
            $arr['msg']= '原密码正确！';
        }else{
            $arr['status'] = 0;
            $arr['msg']= '原密码不正确！';
        }
        $this -> output($arr);
    }

    /**
     * [modifyNewPassword 登录后根据用户ID修改为新密码]
     * @return [json]
     */
    public function modifyNewPassword(){
        $user = session('user');
        $user_id = $user['id'];
        $password = I("password");
        $result = $this->user_model->where("id = $user_id")->save(array('user_pass'=>sp_password($password)));
        if ($result == 1 ) {
            $res['msg'] = '密码修改成功';
            $res['status'] = 1;
        } else if($result == 0 ){
            $res['msg'] = '密码与以前的相同，请重新设置';
            $res['status'] = 0;
        }else{
            $res['msg'] = '重置密码失败';
            $res['status'] =2;
        }
        $this->output($res);
    }

}

